package club.easin.config.db;

import club.easin.utils.Commutils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({Mystring.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MyStringHandleType implements TypeHandler<Mystring> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Mystring mystring, JdbcType jdbcType) throws SQLException {
        String value=null;
        if(preparedStatement!=null){
            value=enString(mystring.toString());
        }
        preparedStatement.setString(i,value);

    }

    @Override
    public Mystring getResult(ResultSet resultSet, String s) throws SQLException {
        String value="";
        Mystring mystring=new Mystring(value);
        value=resultSet.getString(s);
        if(value!=null){
            value=deString(value.toString());
            if(value!=null){
                mystring.setValue(value);
            }
        }
        return mystring;
    }

    @Override
    public Mystring getResult(ResultSet resultSet, int i) throws SQLException {
        String value="";
        Mystring mystring=new Mystring();
        value=resultSet.getString(i);
        if(value!=null){
            mystring.setValue(value);
        }
        return mystring;
    }

    @Override
    public Mystring getResult(CallableStatement callableStatement, int i) throws SQLException {
        String value="";
        Mystring mystring=new Mystring();
        value=callableStatement.getString(i);
        if(value!=null){
            mystring.setValue(value);
        }
        return mystring;
    }

    public String enString(String value){
        value= Commutils.encod(value);
        return value;
    }

    public String deString(String value){
        value= Commutils.dencod(value);
        return value;
    }
}
